const app = getApp();
Page({
  data: {
    orders: [],          // 订单列表数据
  },
  onLoad() {
    this.loadOrders();
  },
  onShow(){
    this.loadOrders();
  },
  // 加载订单数据
  async loadOrders() {
    this.setData({ orders: [] });
    const orders = await this.getOrdersList();
    const ordersWithDetails = await this.getOrdersDetails(orders);
    
    this.setData({
      orders: ordersWithDetails.map(order => ({
        ...order,
        orderTime: this.formatDate(order.orderTime)
      })),
    });
  },

  // 获取订单列表
  getOrdersList() {
    return new Promise((resolve, reject) => {
      const userId=app.globalData.userInfo.id;
      const token=app.globalData.token;
      const timestamp = new Date().getTime();
      wx.request({
        url: `http://localhost:8080/manage/orders/list?t=${timestamp}`,
        method: 'GET',
        data : { userId: userId },
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        success: res => {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data.rows); // 根据实际返回结构调整
          } else {
            reject(new Error('获取订单列表失败'));
          }
        },
        fail: () => reject(new Error('网络请求失败'))
      });
    });
  },

  // 批量获取订单详情
  async getOrdersDetails(orders) {
    const promises = orders.map(order => 
      this.getOrderDetail(order.id).then(details => {
        // 计算实付金额
        console.log('订单详情数据:', details);
        const totalAmount = details.reduce((sum, item) => {
          return sum + (Number(item.amount) * parseInt(item.number));
          }, 0).toFixed(2);
        return {
          ...order,
          amount: totalAmount, // 用计算值覆盖原始金额
          items: details.map(d => ({
            name: d.name,
            price: d.amount.toFixed(2),
            quantity: d.number
          }))
        }
      })
    );
    return Promise.all(promises);
  },

  // 获取单个订单详情
  getOrderDetail(orderId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/manage/detail/list`,
        method: 'GET',
        data: { orderId },
        success: res => {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data.rows); // 根据实际返回结构调整
          } else {
            reject(new Error('获取详情失败'));
          }
        },
        fail: () => reject(new Error('网络请求失败'))
      });
    });
  },

  // 日期格式化方法
  formatDate(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  },

  toComment(e) {
    const OrderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: `/pages/comment/comment?OrderId=${OrderId}`,
    });
  }
});